import os
from jsonschema import validate, ValidationError
import subprocess
import time
import json
import re
import requests
import hashlib
import getpass
from pathlib import Path
from datetime import datetime
import difflib
import webbrowser
import traceback
import threading
import queue
import colorama
colorama.init()

class UserManager:
    """用户管理系统"""
    def __init__(self, data_dir=None):
        # 使用当前工作目录
        if data_dir is None:
            self.data_dir = Path.cwd() / "user_data"
        else:
            self.data_dir = Path(data_dir)
        
        # 确保目录存在
        self.data_dir.mkdir(parents=True, exist_ok=True)
        
        self.users_file = self.data_dir / "users.json"
        self.current_user = None
        self.users = self.load_users()
    
    def load_users(self):
        """加载用户数据"""
        if self.users_file.exists():
            try:
                with open(self.users_file, "r") as f:
                    return json.load(f)
            except:
                pass
        return {}
    
    def save_users(self):
        """保存用户数据"""
        with open(self.users_file, "w") as f:
            json.dump(self.users, f, indent=2)
    
    def hash_password(self, password):
        """密码哈希处理"""
        return hashlib.sha256(password.encode()).hexdigest()
    
    def register(self, username, password):
        """注册新用户"""
        if username in self.users:
            return False, "用户名已存在"
        
        if len(username) < 3:
            return False, "用户名至少需要3个字符"
        
        if len(password) < 6:
            return False, "密码至少需要6个字符"
        
        # 创建用户目录
        user_dir = self.data_dir / username
        user_dir.mkdir(parents=True, exist_ok=True)
        
        # 保存用户信息
        self.users[username] = {
            "password_hash": self.hash_password(password),
            "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "last_login": None
        }
        
        # 初始化用户配置
        config = {
            "selected_model": None,
            "api_keys": {},
            "auto_save_versions": True,
            "max_history": 10,
            "web_port": 5000,
            "auto_open_browser": True,
            "collaboration_mode": False,
            "team_composition": {
                "architects": 1,
                "developers": 2,
                "qa_engineers": 1,
                "devops_engineers": 1
            },
            "auto_save_context": True,
            "context_save_interval": 5
        }
        config_path = user_dir / "config.json"
        with open(config_path, "w") as f:
            json.dump(config, f, indent=2)
        
        # 创建上下文目录
        context_dir = user_dir / "context"
        context_dir.mkdir(parents=True, exist_ok=True)
        
        self.save_users()
        return True, "注册成功"
    
    def login(self, username, password):
        """用户登录"""
        if username not in self.users:
            return False, "用户名不存在"
        
        stored_hash = self.users[username]["password_hash"]
        if self.hash_password(password) != stored_hash:
            return False, "密码错误"
        
        # 更新最后登录时间
        self.users[username]["last_login"] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.save_users()
        
        self.current_user = username
        return True, f"欢迎回来，{username}!"
    
    def logout(self):
        """用户登出"""
        if self.current_user:
            username = self.current_user
            self.current_user = None
            return True, f"{username} 已登出"
        return False, "没有登录的用户"
    
    def get_user_dir(self):
        """获取当前用户目录"""
        if not self.current_user:
            return None
        return self.data_dir / self.current_user

class AICollaborationManager:
    """AI协作管理器 - 专业角色版本（人工项目经理）"""
    def __init__(self, ai_dev_instance):
        self.ai_dev = ai_dev_instance
        self.agents = {}  # 存储所有AI代理
        self.shared_context = {}  # 共享上下文信息
        self.task_queue = queue.Queue()
        self.results = {}
        self.current_project_plan = None
        self.context_dir = self.ai_dev.user_dir / "context"
        self.context_dir.mkdir(parents=True, exist_ok=True)
        self.context_file = self.context_dir / "shared_context.json"
        self.last_context_save = time.time()
        
        # 项目经理输出JSON Schema
        self.project_plan_schema = {
            "type": "object",
            "properties": {
                "reasoning": {"type": "string"},
                "architecture": {"type": "string"},
                "tasks": {
                    "type": "array",
                    "items": {
                        "type": "object",
                        "properties": {
                            "id": {"type": "string"},
                            "description": {"type": "string"},
                            "priority": {"type": "string", "enum": ["high", "medium", "low"]},
                            "estimated_time": {"type": "number"},
                            "recommended_role": {
                                "type": "string", 
                                "enum": ["architect", "developer", "qa_engineer", "devops_engineer"]
                            },
                            "dependencies": {
                                "type": "array",
                                "items": {"type": "string"}
                            }
                        },
                        "required": ["id", "description", "priority", "recommended_role"]
                    }
                }
            },
            "required": ["reasoning", "tasks"]
        }
        
        # 专业角色的系统提示
        self.role_prompts = {
            "architect": {
                "description": "系统架构设计师",
                "system_prompt": """
你是一个系统架构专家，擅长设计可扩展、高性能的系统架构。
请根据分配的任务设计系统架构，包括技术选型、模块划分和接口设计。
                
请严格按照以下JSON格式返回响应：
                
{
    "reasoning": "思考过程，解释为什么这么做",
    "operations": [
        {
            "type": "操作类型",
            "path": "文件路径",
            "content": "文件内容（可选）",
            "command": "系统命令（可选）",
            "explanation": "操作说明（可选）"
        }
    ]
}
                
支持的操作类型:
- create_file: 创建新文件，需要path和content
- modify_file: 修改文件，需要path和content
- explain: 解释架构设计，需要explanation
"""
            },
            "developer": {
                "description": "全能开发者",
                "system_prompt": """
你是一个全能的AI程序员，能够处理各种开发任务，包括前端、后端、数据库等。
请根据分配的任务生成JSON格式的操作指令。
                
请严格按照以下JSON格式返回响应：
                
{
    "reasoning": "思考过程，解释为什么这么做",
    "operations": [
        {
            "type": "操作类型",
            "path": "文件路径",
            "content": "文件内容（可选）",
            "command": "系统命令（可选）",
            "explanation": "操作说明（可选）"
        }
    ]
}
                
支持的操作类型:
- create_file: 创建新文件，需要path和content
- modify_file: 修改文件，需要path和content
- delete_file: 删除文件，需要path
- run_command: 执行系统命令，需要command
- run_code: 运行代码文件，需要path
- debug_code: 调试代码，需要path（可选content）
- explain: 解释代码或操作，需要explanation
- web_server: 启动Web服务器，需要path（主文件）
- open_browser: 打开浏览器，需要path（URL或文件路径）
"""
            },
            "qa_engineer": {
                "description": "质量保证工程师",
                "system_prompt": """
你是一个质量保证专家，擅长编写测试用例和执行测试。
请根据分配的任务创建测试代码或执行测试。
                
请严格按照以下JSON格式返回响应：
                
{
    "reasoning": "思考过程，解释为什么这么做",
    "operations": [
        {
            "type": "操作类型",
            "path": "文件路径",
            "content": "文件内容（可选）",
            "command": "系统命令（可选）",
            "explanation": "操作说明（可选）"
        }
    ]
}
                
支持的操作类型:
- create_file: 创建测试文件，需要path和content
- modify_file: 修改测试文件，需要path andcontent
- run_command: 执行测试命令，需要command
- run_code: 运行测试代码，需要path
- explain: 解释测试策略，需要explanation
"""
            },
            "devops_engineer": {
                "description": "DevOps工程师",
                "system_prompt": """
你是一个DevOps专家，擅长自动化部署和运维。
请根据分配的任务创建部署脚本或配置文件。
                
请严格按照以下JSON格式返回响应：
                
{
    "reasoning": "思考过程，解释为什么这么做",
    "operations": [
        {
            "type": "操作类型",
            "path": "文件路径",
            "content": "文件内容（可选）",
            "command": "系统命令（可选）",
            "explanation": "操作说明（可选）"
        }
    ]
}
                
支持的操作类型:
- create_file: 创建部署文件，需要path和content
- modify_file: 修改部署文件，需要path和content
- run_command: 执行部署命令，需要command
- explain: 解释部署策略，需要explanation
"""
            }
        }
        
        # 加载已保存的上下文
        self.load_shared_context()
    
    def validate_project_plan(self, plan_data):
        """验证项目计划是否符合JSON Schema"""
        try:
            validate(instance=plan_data, schema=self.project_plan_schema)
            return True, "验证通过"
        except ValidationError as e:
            return False, f"JSON Schema验证失败: {e.message}"
    
    def create_project_plan_ui(self, requirements):
        """创建项目计划的用户界面"""
        print("\n\033[1;36m===== 创建项目计划 =====\033[0m")
        print(f"项目需求: {requirements}")
        print("\n请为项目创建详细计划:")
        
        # 获取项目架构概述
        architecture = input("系统架构概述: ").strip()
        
        # 获取推理过程
        reasoning = input("规划思路: ").strip()
        
        # 创建任务列表
        tasks = []
        task_counter = 1
        
        print("\n\033[1;36m===== 添加任务 =====\033[0m")
        print("输入 'done' 完成添加任务")
        
        while True:
            print(f"\n任务 #{task_counter}:")
            description = input("任务描述: ").strip()
            
            if description.lower() == 'done':
                break
                
            if not description:
                continue
                
            # 获取任务优先级
            priority = input("优先级 (high/medium/low, 默认 medium): ").strip().lower()
            if priority not in ["high", "medium", "low"]:
                priority = "medium"
                
            # 获取预估时间
            try:
                estimated_time = float(input("预估时间 (分钟, 默认 30): ") or "30")
            except ValueError:
                estimated_time = 30
                
            # 获取推荐角色
            print("可选角色: architect, developer, qa_engineer, devops_engineer")
            recommended_role = input("推荐角色 (默认 developer): ").strip().lower()
            if recommended_role not in ["architect", "developer", "qa_engineer", "devops_engineer"]:
                recommended_role = "developer"
                
            # 获取依赖关系
            dependencies_input = input("依赖任务ID (多个用逗号分隔, 默认无): ").strip()
            dependencies = [dep.strip() for dep in dependencies_input.split(",")] if dependencies_input else []
            
            # 创建任务
            task = {
                "id": f"task_{task_counter}",
                "description": description,
                "priority": priority,
                "estimated_time": estimated_time,
                "recommended_role": recommended_role,
                "dependencies": dependencies
            }
            
            tasks.append(task)
            task_counter += 1
        
        # 创建项目计划
        project_plan = {
            "reasoning": reasoning or "人工创建的项目计划",
            "architecture": architecture or "",
            "tasks": tasks
        }
        
        return project_plan
    
    def parse_project_manager_response(self, response):
        """解析项目经理的响应，提取项目计划"""
        # 如果响应已经是字典，直接使用
        if isinstance(response, dict):
            # 验证项目计划
            is_valid, message = self.validate_project_plan(response)
            if is_valid:
                return response
            else:
                print(f"\033[1;33m项目计划验证失败: {message}\033[0m")
                return self.fix_project_plan(response)
        
        # 尝试从文本中提取JSON
        try:
            # 清理响应文本，移除可能的三引号和代码块标记
            cleaned_response = re.sub(r'```(json)?|```', '', response).strip()
            
            # 查找JSON对象的开始和结束位置
            start_idx = cleaned_response.find('{')
            end_idx = cleaned_response.rfind('}')
            
            if start_idx != -1 and end_idx != -1 and end_idx > start_idx:
                json_str = cleaned_response[start_idx:end_idx+1]
                parsed = json.loads(json_str)
                
                # 验证JSON结构
                is_valid, message = self.validate_project_plan(parsed)
                if is_valid:
                    return parsed
                else:
                    print(f"\033[1;33m项目计划验证失败: {message}\033[0m")
                    # 尝试修复JSON
                    return self.fix_project_plan(parsed)
        except json.JSONDecodeError as e:
            print(f"\033[1;31mJSON解析错误: {str(e)}\033[0m")
        
        # 如果所有方法都失败，尝试从文本中提取任务信息
        return self.extract_project_plan_from_text(response)
    
    def extract_project_plan_from_text(self, text):
        """从文本中提取项目计划信息"""
        lines = text.split('\n')
        tasks = []
        reasoning = ""
        architecture = ""
        task_counter = 1
        
        for line in lines:
            line = line.strip()
            
            # 提取推理过程
            if not reasoning and any(keyword in line.lower() for keyword in ["思考", "分析", "计划", "reasoning", "thinking"]):
                reasoning = line
                continue
                
            # 提取架构信息
            if not architecture and any(keyword in line.lower() for keyword in ["架构", "设计", "architecture", "design"]):
                architecture = line
                continue
                
            # 提取任务信息
            if any(keyword in line.lower() for keyword in ["任务", "task", "实现", "开发", "创建", "编写", "build", "create", "implement"]):
                # 跳过包含JSON关键词的行
                if any(json_keyword in line.lower() for json_keyword in ["{", "}", "[", "]", "id", "description"]):
                    continue
                    
                # 根据任务内容推荐角色
                recommended_role = "developer"
                if any(word in line.lower() for word in ["架构", "设计", "系统", "architecture", "design", "system"]):
                    recommended_role = "architect"
                elif any(word in line.lower() for word in ["测试", "质量", "验证", "test", "qa", "quality"]):
                    recommended_role = "qa_engineer"
                elif any(word in line.lower() for word in ["部署", "运维", "服务器", "docker", "kubernetes", "deploy", "devops"]):
                    recommended_role = "devops_engineer"
                
                # 确定优先级
                priority = "medium"
                if any(word in line.lower() for word in ["重要", "紧急", "高优先级", "critical", "urgent", "high"]):
                    priority = "high"
                elif any(word in line.lower() for word in ["低", "later", "low"]):
                    priority = "low"
                
                tasks.append({
                    "id": f"task_{task_counter}",
                    "description": line,
                    "priority": priority,
                    "estimated_time": 30,
                    "recommended_role": recommended_role,
                    "dependencies": []
                })
                task_counter += 1
        
        # 如果没有提取到任务，创建一个默认任务
        if not tasks:
            tasks.append({
                "id": "task_1",
                "description": "实现核心功能",
                "priority": "high",
                "estimated_time": 30,
                "recommended_role": "developer",
                "dependencies": []
            })
        
        return {
            "reasoning": reasoning or "自动生成的项目计划",
            "architecture": architecture or "",
            "tasks": tasks
        }
    
    def fix_project_plan(self, plan_data):
        """修复项目计划中的常见问题"""
        fixed_plan = {
            "reasoning": plan_data.get("reasoning", "自动生成的项目计划"),
            "architecture": plan_data.get("architecture", ""),
            "tasks": []
        }
        
        # 确保tasks是列表
        tasks = plan_data.get("tasks", [])
        if not isinstance(tasks, list):
            # 尝试从字典中提取任务
            if isinstance(tasks, dict):
                tasks = [tasks]
            else:
                tasks = []
        
        # 修复每个任务
        for i, task in enumerate(tasks):
            if not isinstance(task, dict):
                continue
                
            # 确保任务ID唯一
            task_id = task.get("id")
            if not task_id or any(t.get("id") == task_id for t in fixed_plan["tasks"]):
                task_id = f"task_{i+1}"
            
            # 确保描述不为空
            description = task.get("description")
            if not description:
                description = f"任务 {i+1}"
            
            # 验证和修复优先级
            priority = task.get("priority", "medium")
            if priority not in ["high", "medium", "low"]:
                # 根据描述猜测优先级
                if any(word in description.lower() for word in ["重要", "紧急", "高优先级", "critical", "urgent", "high"]):
                    priority = "high"
                elif any(word in description.lower() for word in ["低", "later", "low"]):
                    priority = "low"
                else:
                    priority = "medium"
            
            # 验证和修复推荐角色
            recommended_role = task.get("recommended_role", "developer")
            if recommended_role not in ["architect", "developer", "qa_engineer", "devops_engineer"]:
                # 根据任务描述猜测角色
                if any(word in description.lower() for word in ["架构", "设计", "系统", "architecture", "design", "system"]):
                    recommended_role = "architect"
                elif any(word in description.lower() for word in ["测试", "质量", "验证", "test", "qa", "quality"]):
                    recommended_role = "qa_engineer"
                elif any(word in description.lower() for word in ["部署", "运维", "服务器", "docker", "kubernetes", "deploy", "devops"]):
                    recommended_role = "devops_engineer"
                else:
                    recommended_role = "developer"
            
            # 确保依赖关系是列表
            dependencies = task.get("dependencies", [])
            if not isinstance(dependencies, list):
                dependencies = []
            
            # 确保预估时间是数字
            estimated_time = task.get("estimated_time", 30)
            if not isinstance(estimated_time, (int, float)):
                estimated_time = 30
            
            fixed_task = {
                "id": task_id,
                "description": description,
                "priority": priority,
                "estimated_time": estimated_time,
                "recommended_role": recommended_role,
                "dependencies": dependencies
            }
            
            fixed_plan["tasks"].append(fixed_task)
        
        return fixed_plan
    
    def load_shared_context(self):
        """加载共享上下文"""
        if self.context_file.exists():
            try:
                with open(self.context_file, "r", encoding="utf-8") as f:
                    self.shared_context = json.load(f)
                print(f"\033[1;32m已加载共享上下文: {len(self.shared_context)}条记录\033[0m")
            except Exception as e:
                print(f"\033[1;31m加载共享上下文失败: {str(e)}\033[0m")
                self.shared_context = {}
        else:
            self.shared_context = {}
    
    def save_shared_context(self):
        """保存共享上下文"""
        try:
            with open(self.context_file, "w", encoding="utf-8") as f:
                json.dump(self.shared_context, f, indent=2, ensure_ascii=False)
            
            # 创建上下文备份
            backup_file = self.context_dir / f"shared_context_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
            with open(backup_file, "w", encoding="utf-8") as f:
                json.dump(self.shared_context, f, indent=2, ensure_ascii=False)
                
            # 限制备份文件数量
            self.cleanup_context_backups()
            
            return True
        except Exception as e:
            print(f"\033[1;31m保存共享上下文失败: {str(e)}\033[0m")
            return False
    
    def cleanup_context_backups(self, max_backups=5):
        """清理旧的上下文备份"""
        try:
            backup_files = list(self.context_dir.glob("shared_context_backup_*.json"))
            if len(backup_files) > max_backups:
                # 按修改时间排序，删除最旧的备份
                backup_files.sort(key=lambda x: x.stat().st_mtime)
                for i in range(len(backup_files) - max_backups):
                    backup_files[i].unlink()
        except Exception as e:
            print(f"\033[1;31m清理上下文备份失败: {str(e)}\033[0m")
    
    def auto_save_context_check(self):
        """检查是否需要自动保存上下文"""
        if not self.ai_dev.config.get("auto_save_context", True):
            return False
            
        current_time = time.time()
        save_interval = self.ai_dev.config.get("context_save_interval", 5) * 60  # 转换为秒
        
        if current_time - self.last_context_save >= save_interval:
            if self.save_shared_context():
                self.last_context_save = current_time
                print("\033[1;35m已自动保存共享上下文\033[0m")
                return True
        return False
    
    def initialize_agents(self, requirements):
        """根据需求初始化AI代理团队"""
        # 不再创建项目经理，因为现在是人工项目经理
        
        # 获取团队配置
        team_config = self.ai_dev.config.get("team_composition", {
            "architects": 1,
            "developers": 2,
            "qa_engineers": 1,
            "devops_engineers": 1
        })
        
        # 创建架构师
        for i in range(team_config.get("architects", 1)):
            architect_id = f"architect_{i+1}"
            self.agents[architect_id] = {
                "description": self.role_prompts["architect"]["description"],
                "system_prompt": self.role_prompts["architect"]["system_prompt"],
                "tasks": [],
                "status": "idle",
                "results": []
            }
        
        # 创建开发者
        for i in range(team_config.get("developers", 2)):
            developer_id = f"developer_{i+1}"
            self.agents[developer_id] = {
                "description": self.role_prompts["developer"]["description"],
                "system_prompt": self.role_prompts["developer"]["system_prompt"],
                "tasks": [],
                "status": "idle",
                "results": []
            }
        
        # 创建QA工程师
        for i in range(team_config.get("qa_engineers", 1)):
            qa_id = f"qa_engineer_{i+1}"
            self.agents[qa_id] = {
                "description": self.role_prompts["qa_engineer"]["description"],
                "system_prompt": self.role_prompts["qa_engineer"]["system_prompt"],
                "tasks": [],
                "status": "idle",
                "results": []
            }
        
        # 创建DevOps工程师
        for i in range(team_config.get("devops_engineers", 1)):
            devops_id = f"devops_engineer_{i+1}"
            self.agents[devops_id] = {
                "description": self.role_prompts["devops_engineer"]["description"],
                "system_prompt": self.role_prompts["devops_engineer"]["system_prompt"],
                "tasks": [],
                "status": "idle",
                "results": []
            }
        
        team_members = list(self.agents.keys())
        print(f"\033[1;32m已初始化AI团队: {len(team_members)}名专业成员\033[0m")
        
        # 检查是否需要自动保存上下文
        self.auto_save_context_check()
        
        return team_members
    
    def update_shared_context(self, role, data):
        """更新共享上下文"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        # 如果角色已经存在上下文，更新它；否则创建新条目
        if role in self.shared_context:
            self.shared_context[role].update({
                "last_updated": timestamp,
                "data": data
            })
        else:
            self.shared_context[role] = {
                "created_at": timestamp,
                "last_updated": timestamp,
                "data": data
            }
        
        print(f"\033[1;35m[{role}] 更新了共享上下文\033[0m")
        
        # 检查是否需要自动保存
        self.auto_save_context_check()
    
    def get_shared_context(self, requesting_role):
        """获取共享上下文摘要"""
        if not self.shared_context:
            return "尚无共享上下文信息"
        
        context_summary = "共享上下文摘要:\n"
        for role, context in self.shared_context.items():
            if role != requesting_role:  # 不包含请求者自己的上下文
                # 格式化上下文信息
                context_data = context.get("data", {})
                context_str = str(context_data)
                
                # 如果是项目计划，提取关键信息
                if "reasoning" in context_data and "tasks" in context_data:
                    context_str = f"项目计划: {context_data['reasoning'][:50]}... ({len(context_data['tasks'])}个任务)"
                
                context_summary += f"- {role} (更新于 {context.get('last_updated', '未知')}): {context_str[:100]}...\n"
        
        return context_summary
    
    def clear_shared_context(self):
        """清空共享上下文"""
        self.shared_context = {}
        if self.context_file.exists():
            self.context_file.unlink()
        print("\033[1;33m已清空共享上下文\033[0m")
        return True
    
    def export_shared_context(self, file_path=None):
        """导出共享上下文到文件"""
        if not file_path:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            file_path = self.context_dir / f"shared_context_export_{timestamp}.json"
        
        try:
            with open(file_path, "w", encoding="utf-8") as f:
                json.dump(self.shared_context, f, indent=2, ensure_ascii=False)
            return f"共享上下文已导出到: {file_path}"
        except Exception as e:
            return f"导出共享上下文失败: {str(e)}"
    
    def import_shared_context(self, file_path):
        """从文件导入共享上下文"""
        try:
            if not file_path.exists():
                return "文件不存在"
            
            with open(file_path, "r", encoding="utf-8") as f:
                imported_context = json.load(f)
            
            # 合并上下文
            self.shared_context.update(imported_context)
            
            # 保存更新后的上下文
            self.save_shared_context()
            
            return f"已从 {file_path} 导入共享上下文: {len(imported_context)}条记录"
        except Exception as e:
            return f"导入共享上下文失败: {str(e)}"
    
    def orchestrate_development(self, requirements):
        """协调开发过程 - 人工项目经理版本"""
        print(f"\033[1;34m=== 开始协作开发: {requirements} ===\033[0m")
        
        # 1. 初始化团队
        roles = self.initialize_agents(requirements)
        print(f"\033[1;33m团队组成: {', '.join(roles)}\033[0m")
        
        # 2. 人工项目经理制定计划
        print("\033[1;33m请创建项目计划...\033[0m")
        
        # 创建项目计划
        self.current_project_plan = self.create_project_plan_ui(requirements)
        
        # 验证项目计划
        is_valid, message = self.validate_project_plan(self.current_project_plan)
        if not is_valid:
            print(f"\033[1;33m项目计划验证警告: {message}\033[0m")
            # 尝试修复项目计划
            self.current_project_plan = self.fix_project_plan(self.current_project_plan)
        
        # 更新共享上下文
        self.update_shared_context("human_project_manager", self.current_project_plan)
        
        print(f"\033[1;32m成功创建项目计划: {len(self.current_project_plan.get('tasks', []))}个任务\033[0m")
        print(f"\033[1;32m架构概述: {self.current_project_plan.get('architecture', '无')}\033[0m")
        
        # 显示任务分配情况
        role_counts = {}
        for task in self.current_project_plan.get("tasks", []):
            role = task.get("recommended_role", "developer")
            role_counts[role] = role_counts.get(role, 0) + 1
        
        print(f"\033[1;32m任务分配: {', '.join([f'{k}: {v}' for k, v in role_counts.items()])}\033[0m")
        
        # 确认是否继续执行
        confirm = input("\n是否开始执行任务? (y/n, 默认 y): ").strip().lower()
        if confirm not in ["y", "yes", ""]:
            return {"reasoning": "用户取消了任务执行", "integration": "任务执行已取消"}
        
        # 3. 执行任务
        print("\033[1;33m开始执行任务...\033[0m")
        all_results = {"human_project_manager": {"reasoning": "人工创建的项目计划", "results": []}}
        
        # 按优先级排序任务
        sorted_tasks = self.prioritize_tasks(self.current_project_plan.get("tasks", []))
        
        # 执行任务
        for task in sorted_tasks:
            # 选择最适合的角色
            recommended_role = task.get("recommended_role", "developer")
            role_id = self.select_best_role_for_task(task, recommended_role)
            
            if not role_id:
                print(f"\033[1;31m没有可用的角色处理任务: {task['description']}\033[0m")
                continue
                
            # 准备任务描述，包含共享上下文
            shared_context = self.get_shared_context(role_id)
            task_description = f"""
项目需求: {requirements}
当前任务: {task['description']}
优先级: {task.get('priority', 'medium')}
预估时间: {task.get('estimated_time', '未知')}分钟

{shared_context}

请完成此任务并提供具体实现。
            """
            
            # 分配任务
            print(f"\033[1;33m分配任务给 {role_id}: {task['description'][:50]}...\033[0m")
            task_result = self.assign_task(role_id, task_description)
            all_results[f"task_{task['id']}_{role_id}"] = task_result
            
            # 更新共享上下文
            if "error" not in task_result:
                self.update_shared_context(role_id, task_result)
                
            # 检查是否需要自动保存上下文
            self.auto_save_context_check()
        
        # 4. 整合结果
        print("\033[1;33m整合开发结果...\033[0m")
        final_result = self.integrate_results(all_results)
        
        # 保存最终上下文
        self.save_shared_context()
        
        return final_result
    
    def prioritize_tasks(self, tasks):
        """按优先级排序任务"""
        priority_order = {"high": 0, "medium": 1, "low": 2}
        return sorted(tasks, key=lambda x: priority_order.get(x.get("priority", "medium"), 1))
    
    def select_best_role_for_task(self, task, recommended_role):
        """选择最适合处理任务的角色"""
        # 首先尝试推荐的角色类型
        role_prefix = recommended_role
        matching_roles = [role for role in self.agents.keys() if role.startswith(role_prefix)]
        
        # 优先选择空闲的角色
        for role in matching_roles:
            if self.agents[role]["status"] == "idle":
                return role
        
        # 如果没有空闲的，选择任务最少的
        if matching_roles:
            return min(matching_roles, key=lambda x: len(self.agents[x]["tasks"]))
        
        # 如果推荐的角色类型都不可用，尝试其他开发者
        developer_roles = [role for role in self.agents.keys() if role.startswith("developer")]
        for role in developer_roles:
            if self.agents[role]["status"] == "idle":
                return role
        
        # 最后选择任何可用的角色
        available_roles = list(self.agents.keys())
        if available_roles:
            return min(available_roles, key=lambda x: len(self.agents[x]["tasks"]))
        
        return None
    
    def assign_task(self, role, task_description):
        """分配任务给特定角色的AI"""
        print(f"\033[1;33m[{role}] 执行任务: {task_description[:50]}...\033[0m")
        
        # 使用特定角色的系统提示
        system_prompt = self.agents[role]["system_prompt"]
        
        # 调用AI
        response = self.ai_dev.call_ai_api(task_description, system_prompt)
        if response:
            # 使用统一的解析方法
            parsed = self.ai_dev.parse_ai_response(response)
            
            # 确保解析结果包含必要的字段
            if "operations" not in parsed:
                parsed["operations"] = []
            if "reasoning" not in parsed:
                parsed["reasoning"] = "无推理过程"
                
            results = self.ai_dev.execute_operations(parsed.get("operations", []))
            
            # 记录任务完成
            self.agents[role]["status"] = "completed"
            self.agents[role]["tasks"].append(task_description)
            self.agents[role]["results"].append({
                "task": task_description,
                "result": results
            })
            
            return {
                "role": role,
                "reasoning": parsed.get("reasoning", ""),
                "results": results
            }
        
        return {"role": role, "error": "AI调用失败"}
    
    def integrate_results(self, all_results):
        """整合所有AI的工作成果"""
        integration_text = "\033[1;34m=== 项目开发完成 ===\033[0m\n\n"
        
        # 添加项目计划
        if "human_project_manager" in all_results:
            pm_result = all_results["human_project_manager"]
            integration_text += f"\033[1;32m项目计划:\033[0m {pm_result.get('reasoning', '')}\n\n"
        
        # 添加各任务结果
        integration_text += "\033[1;32m任务执行详情:\033[0m\n"
        
        for key, result in all_results.items():
            if key != "human_project_manager" and "error" not in result:
                role_desc = self.agents.get(result.get('role'), {}).get('description', result.get('role'))
                integration_text += f"\n\033[1;33m{role_desc}:\033[0m\n"
                integration_text += f"推理: {result.get('reasoning', '')}\n"
                
                # 添加操作结果
                for op_result in result.get('results', []):
                    status = "✓" if op_result.get('success') else "✗"
                    integration_text += f"  {status} {op_result.get('type')}: {op_result.get('output', '')}\n"
        
        # 添加团队状态
        integration_text += "\n\033[1;32m团队状态总结:\033[0m\n"
        for role, agent in self.agents.items():
            status = "✓" if agent["status"] == "completed" else "✗"
            integration_text += f"{agent['description']}: {status} (完成任务: {len(agent['tasks'])})\n"
        
        # 添加上下文状态
        integration_text += f"\n\033[1;32m共享上下文状态:\033[0m {len(self.shared_context)}条记录\n"
        
        return {
            "reasoning": "多AI协作开发完成",
            "integration": integration_text,
            "detailed_results": all_results
        }

class AIDeveloper:
    OPERATION_TYPES = [
        "create_file", "modify_file", "delete_file", 
        "run_command", "run_code", "debug_code",
        "explain", "web_server", "open_browser"
    ]
    
    def __init__(self, user_dir):
        self.user_dir = Path(user_dir)
        self.workspace = self.user_dir / "projects"
        self.workspace.mkdir(parents=True, exist_ok=True)
        self.versions_dir = self.user_dir / "versions"
        self.versions_dir.mkdir(parents=True, exist_ok=True)
        self.project_history = []
        self.current_file = None
        self.current_project = "default"
        self.current_project_type = "python"
        self.config = self.load_config()
        self.web_process = None
        self.web_port = self.config.get("web_port", 5000)
        
        # 协作模式相关
        self.collaboration_mode = self.config.get("collaboration_mode", False)
        self.collaboration_manager = None
        if self.collaboration_mode:
            self.collaboration_manager = AICollaborationManager(self)
        
        # 支持的AI模型服务
        self.supported_models = {
            "deepseek": {
                "name": "DeepSeek",
                "endpoint": "https://api.deepseek.com/v1/chat/completions",
                "model": "deepseek-chat"
            },
            "wenxin": {
                "name": "文心千帆",
                "endpoint": "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions",
                "model": "ERNIE-Bot-4"
            }
        }
    
    def load_config(self):
        """加载用户配置"""
        config_path = self.user_dir / "config.json"
        if config_path.exists():
            try:
                with open(config_path, "r") as f:
                    return json.load(f)
            except:
                pass
        
        # 默认配置
        default_config = {
            "selected_model": None,
            "api_keys": {},
            "auto_save_versions": True,
            "max_history": 10,
            "web_port": 5000,
            "auto_open_browser": True,
            "collaboration_mode": False
        }
        
        # 保存默认配置
        with open(config_path, "w") as f:
            json.dump(default_config, f, indent=2)
        
        return default_config
    
    def save_config(self):
        """保存用户配置"""
        config_path = self.user_dir / "config.json"
        with open(config_path, "w") as f:
            json.dump(self.config, f, indent=2)
    
    def display_banner(self, username):
        print("\033[1;34m" + "=" * 70)
        print(f"        AI 程序员智能开发系统 v7.0 (多AI协作版)")
        print("=" * 70 + "\033[0m")
        print(f"用户: \033[1;32m{username}\033[0m")
        print(f"工作区: \033[1;33m{self.workspace}\033[0m")
        
        if self.config["selected_model"]:
            model_name = self.supported_models.get(self.config["selected_model"], {}).get("name", "未知模型")
            print(f"当前模型: \033[1;32m{model_name}\033[0m")
        else:
            print("当前模型: \033[1;31m未配置\033[0m (使用内置逻辑)")
        
        # 显示协作模式状态
        if self.collaboration_mode:
            print(f"协作模式: \033[1;32m已启用\033[0m")
        else:
            print(f"协作模式: \033[1;31m未启用\033[0m")
        
        print("\n指令格式: JSON对象，包含以下操作类型:")
        for op in self.OPERATION_TYPES:
            print(f" - {op}")
        print("\n协作命令:")
        print(" - 'team on': 启用协作模式")
        print(" - 'team off': 禁用协作模式") 
        print(" - 'team status': 查看团队状态")
        print("\n输入 'exit' 退出系统")
        print("输入 'help' 显示帮助")
    
    def enable_collaboration(self):
        """启用协作模式"""
        self.collaboration_mode = True
        self.config["collaboration_mode"] = True
        self.save_config()
        self.collaboration_manager = AICollaborationManager(self)
        return "\033[1;32m已启用多AI协作模式\033[0m"
    
    def disable_collaboration(self):
        """禁用协作模式"""
        self.collaboration_mode = False
        self.config["collaboration_mode"] = False
        self.save_config()
        self.collaboration_manager = None
        return "\033[1;33m已禁用多AI协作模式\033[0m"
    
    def get_team_status(self):
        """获取团队状态"""
        if not self.collaboration_mode or not self.collaboration_manager:
            return "协作模式未启用"
        
        status = "\033[1;34m=== 团队状态 ===\033[0m\n"
        for role, agent in self.collaboration_manager.agents.items():
            status += f"{role}: {agent['status']} (任务数: {len(agent['results'])})\n"
        
        # 添加上下文信息
        if hasattr(self.collaboration_manager, 'shared_context') and self.collaboration_manager.shared_context:
            status += "\n\033[1;34m共享上下文:\033[0m\n"
            for role, context in self.collaboration_manager.shared_context.items():
                status += f"- {role}: {str(context['data'])[:50]}...\n"
        
        return status
    
    def log_history(self, action, content, details=None):
        """记录开发历史"""
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
        entry = {
            "time": timestamp,
            "action": action,
            "content": content,
            "details": details
        }
        self.project_history.append(entry)
        
        # 保持历史记录不超过最大值
        if len(self.project_history) > self.config.get("max_history", 20):
            self.project_history.pop(0)
        
        # 保存历史到文件
        history_path = self.user_dir / "dev_history.json"
        with open(history_path, "w") as f:
            json.dump(self.project_history, f, indent=2)
    
    def save_version(self, action="自动保存"):
        """保存当前代码版本"""
        if not self.current_file or not self.current_file.exists():
            return None
        
        # 读取当前文件内容
        with open(self.current_file, "r", encoding="utf-8") as f:
            current_code = f.read()
        
        # 创建版本文件名
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        version_file = self.versions_dir / f"{self.current_project}_{timestamp}.py"
        
        # 保存版本
        with open(version_file, "w", encoding="utf-8") as f:
            f.write(current_code)
        
        return version_file.name
    
    def call_ai_api(self, prompt, system_prompt=None):
        """调用选定的AI模型API"""
        if not self.config["selected_model"] or not self.config["api_keys"].get(self.config["selected_model"]):
            return None
        
        model_info = self.supported_models[self.config["selected_model"]]
        api_key = self.config["api_keys"][self.config["selected_model"]]
        
        headers = {
            "Content-Type": "application/json"
        }
        
        # 统一系统提示格式
        if not system_prompt:
            system_prompt = """
            你是一个AI程序员，需要根据用户需求生成JSON格式的操作指令。
            请严格按照以下JSON格式返回响应：
            
            {
                "reasoning": "思考过程，解释为什么这么做",
                "operations": [
                    {
                        "type": "操作类型",
                        "path": "文件路径",
                        "content": "文件内容（可选）",
                        "command": "系统命令（可选）",
                        "explanation": "操作说明（可选）"
                    },
                    // 更多操作...
                ]
            }
            
            支持的操作类型:
            - create_file: 创建新文件，需要path和content
            - modify_file: 修改文件，需要path和content
            - delete_file: 删除文件，需要path
            - run_command: 执行系统命令，需要command
            - run_code: 运行代码文件，需要path
            - debug_code: 调试代码，需要path（可选content）
            - explain: 解释代码或操作，需要explanation
            - web_server: 启动Web服务器，需要path（主文件）
            - open_browser: 打开浏览器，需要path（URL或文件路径）
            """
        
        messages = [
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": prompt}
        ]
        
        if self.config["selected_model"] == "deepseek":
            headers["Authorization"] = f"Bearer {api_key}"
            payload = {
                "model": model_info["model"],
                "messages": messages,
                "temperature": 0.3,
                "max_tokens": 4000,
                "response_format": {"type": "json_object"}
            }
        elif self.config["selected_model"] == "wenxin":
            payload = {
                "messages": messages,
                "temperature": 0.3,
                "max_tokens": 4000
            }
            # 文心千帆API需要access_token
            access_token = self.get_wenxin_access_token(api_key)
            if not access_token:
                return None
            endpoint = f"{model_info['endpoint']}?access_token={access_token}"
        else:
            return None
        
        try:
            response = requests.post(
                model_info["endpoint"] if self.config["selected_model"] == "deepseek" else endpoint,
                headers=headers,
                json=payload,
                timeout=60
            )
            
            if response.status_code == 200:
                result = response.json()
                if self.config["selected_model"] == "deepseek":
                    return result["choices"][0]["message"]["content"]
                elif self.config["selected_model"] == "wenxin":
                    return result["result"]
            else:
                print(f"API错误: {response.status_code} - {response.text}")
                return None
        except Exception as e:
            print(f"API调用异常: {str(e)}")
            return None
    
    def get_wenxin_access_token(self, api_key):
        """获取文心千帆的access_token"""
        if ":" not in api_key:
            return None
        
        api_key, secret_key = api_key.split(":", 1)
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {
            "grant_type": "client_credentials",
            "client_id": api_key,
            "client_secret": secret_key
        }
        
        try:
            response = requests.get(url, params=params, timeout=10)
            if response.status_code == 200:
                return response.json().get("access_token")
        except:
            pass
        return None
    
    def parse_ai_response(self, response):
        """解析AI的JSON响应 - 统一解析方法"""
        # 如果响应已经是字典，直接返回
        if isinstance(response, dict):
            return response
            
        # 尝试从文本中提取JSON
        try:
            # 查找JSON对象的开始和结束位置
            start_idx = response.find('{')
            end_idx = response.rfind('}')
            
            if start_idx != -1 and end_idx != -1 and end_idx > start_idx:
                json_str = response[start_idx:end_idx+1]
                parsed = json.loads(json_str)
                
                # 确保包含必要的字段
                if "operations" not in parsed:
                    parsed["operations"] = []
                if "reasoning" not in parsed:
                    parsed["reasoning"] = "无推理过程"
                    
                return parsed
        except json.JSONDecodeError as e:
            print(f"JSON解析错误: {str(e)}")
            # 继续尝试其他方法
        
        # 尝试使用正则表达式查找JSON
        try:
            json_pattern = r'\{.*?\}'
            matches = re.findall(json_pattern, response, re.DOTALL)
            if matches:
                # 尝试解析每个匹配项
                for match in matches:
                    try:
                        parsed = json.loads(match)
                        if "operations" in parsed or "reasoning" in parsed:
                            # 确保包含必要的字段
                            if "operations" not in parsed:
                                parsed["operations"] = []
                            if "reasoning" not in parsed:
                                parsed["reasoning"] = "无推理过程"
                            return parsed
                    except:
                        continue
        except:
            pass
        
        # 如果所有方法都失败，返回默认结构
        print(f"无法解析AI响应: {response[:200]}...")
        return {
            "reasoning": "无法解析AI响应",
            "operations": [{
                "type": "explain",
                "explanation": f"AI返回了无法解析的响应: {response[:200]}..."
            }]
        }
    
    def execute_operations(self, operations):
        """执行AI返回的操作指令"""
        results = []
        
        for op in operations:
            op_type = op.get("type", "")
            path = op.get("path", "")
            content = op.get("content", "")
            command = op.get("command", "")
            explanation = op.get("explanation", "")
            
            result = {"type": op_type, "success": False, "output": ""}
            
            try:
                # 创建文件
                if op_type == "create_file":
                    full_path = self.workspace / path
                    full_path.parent.mkdir(parents=True, exist_ok=True)
                    
                    # 检查文件是否已存在
                    if full_path.exists():
                        result["output"] = f"文件已存在: {path}"
                    else:
                        with open(full_path, "w", encoding="utf-8") as f:
                            f.write(content)
                        result["success"] = True
                        result["output"] = f"文件创建成功: {path}"
                        self.current_file = full_path
                
                # 修改文件
                elif op_type == "modify_file":
                    full_path = self.workspace / path
                    if full_path.exists():
                        # 保存当前版本
                        if self.config["auto_save_versions"]:
                            self.save_version("修改前保存")
                        
                        with open(full_path, "w", encoding="utf-8") as f:
                            f.write(content)
                        result["success"] = True
                        result["output"] = f"文件修改成功: {path}"
                        self.current_file = full_path
                    else:
                        result["output"] = f"文件不存在: {path}"
                
                # 删除文件
                elif op_type == "delete_file":
                    full_path = self.workspace / path
                    if full_path.exists():
                        # 保存当前版本
                        if self.config["auto_save_versions"]:
                            self.save_version("删除前保存")
                            
                        full_path.unlink()
                        result["success"] = True
                        result["output"] = f"文件删除成功: {path}"
                    else:
                        result["output"] = f"文件不存在: {path}"
                
                # 执行系统命令
                elif op_type == "run_command":
                    try:
                        process = subprocess.run(
                            command,
                            shell=True,
                            capture_output=True,
                            text=True,
                            timeout=30
                        )
                        result["output"] = process.stdout
                        if process.returncode == 0:
                            result["success"] = True
                        else:
                            result["output"] += f"\n错误: {process.stderr}"
                    except Exception as e:
                        result["output"] = f"命令执行失败: {str(e)}"
                
                # 运行代码
                elif op_type == "run_code":
                    full_path = self.workspace / path
                    if full_path.exists():
                        try:
                            process = subprocess.run(
                                ["python", str(full_path)],
                                capture_output=True,
                                text=True,
                                timeout=30
                            )
                            result["output"] = process.stdout
                            if process.returncode == 0:
                                result["success"] = True
                            else:
                                result["output"] += f"\n错误: {process.stderr}"
                        except Exception as e:
                            result["output"] = f"代码运行失败: {str(e)}"
                    else:
                        result["output"] = f"文件不存在: {path}"
                
                # 调试代码
                elif op_type == "debug_code":
                    # 这里简化处理，实际应该调用调试逻辑
                    result["output"] = "调试功能将在后续版本实现"
                
                # 解释说明
                elif op_type == "explain":
                    result["success"] = True
                    result["output"] = explanation
                
                # 启动Web服务器
                elif op_type == "web_server":
                    full_path = self.workspace / path
                    if full_path.exists():
                        # 停止现有服务器
                        if self.web_process and self.web_process.poll() is None:
                            self.web_process.terminate()
                        
                        # 启动新服务器
                        self.web_process = subprocess.Popen(
                            ["python", str(full_path)],
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE,
                            text=True
                        )
                        time.sleep(2)
                        
                        if self.web_process.poll() is None:
                            result["success"] = True
                            result["output"] = f"Web服务器已启动: http://localhost:{self.web_port}"
                        else:
                            error = self.web_process.stderr.read() if self.web_process.stderr else "启动失败"
                            result["output"] = f"Web服务器启动失败: {error}"
                    else:
                        result["output"] = f"文件不存在: {path}"
                
                # 打开浏览器
                elif op_type == "open_browser":
                    if path.startswith("http"):
                        webbrowser.open(path)
                        result["success"] = True
                        result["output"] = f"已打开浏览器: {path}"
                    else:
                        full_path = self.workspace / path
                        if full_path.exists():
                            webbrowser.open(f"file://{full_path.resolve()}")
                            result["success"] = True
                            result["output"] = f"已打开文件: {path}"
                        else:
                            result["output"] = f"文件不存在: {path}"
                
                # 未知操作类型
                else:
                    result["output"] = f"未知操作类型: {op_type}"
            
            except Exception as e:
                result["output"] = f"操作执行异常: {str(e)}\n{traceback.format_exc()}"
            
            results.append(result)
        
        return results
    
    def generate_instructions(self, requirements):
        """根据需求生成操作指令并执行"""
        # 构建提示
        prompt = f"""
        用户需求: {requirements}
        
        当前工作区: {self.workspace}
        当前项目: {self.current_project}
        当前文件: {self.current_file}
        
        请生成JSON格式的操作指令来满足用户需求。
        """
        
        # 调用AI API
        ai_response = self.call_ai_api(prompt)
        if not ai_response:
            return {
                "reasoning": "AI调用失败",
                "operations": [{
                    "type": "explain",
                    "explanation": "无法调用AI服务，请检查API配置"
                }]
            }, []
        
        # 解析AI响应
        instructions = self.parse_ai_response(ai_response)
        
        # 执行操作
        results = self.execute_operations(instructions.get("operations", []))
        
        return instructions, results
    
    def configure_team(self):
        """配置团队组成"""
        print("\n\033[1;36m===== 团队配置 =====\033[0m")
        print("请设置团队中各角色的数量:")
        
        try:
            architects = int(input("架构师数量 (默认 1): ") or "1")
            developers = int(input("开发者数量 (默认 2): ") or "2")
            qa_engineers = int(input("QA工程师数量 (默认 1): ") or "1")
            devops_engineers = int(input("DevOps工程师数量 (默认 1): ") or "1")
            
            self.config["team_composition"] = {
                "architects": max(0, architects),
                "developers": max(0, developers),
                "qa_engineers": max(0, qa_engineers),
                "devops_engineers": max(0, devops_engineers)
            }
            
            self.save_config()
            return f"团队配置已更新: {self.config['team_composition']}"
        except ValueError:
            return "输入无效，请输入数字"
    
    def configure_context_settings(self):
        """配置上下文设置"""
        print("\n\033[1;36m===== 上下文配置 =====\033[0m")
        
        try:
            auto_save = input("自动保存上下文 (y/n, 默认 y): ").lower()
            if auto_save in ["y", "yes", ""]:
                self.config["auto_save_context"] = True
            else:
                self.config["auto_save_context"] = False
            
            interval = input("自动保存间隔 (分钟, 默认 5): ") or "5"
            self.config["context_save_interval"] = max(1, int(interval))
            
            self.save_config()
            return f"上下文配置已更新: 自动保存={self.config['auto_save_context']}, 间隔={self.config['context_save_interval']}分钟"
        except ValueError:
            return "输入无效，请输入数字"
    
    def manage_context(self):
        """管理共享上下文"""
        print("\n\033[1;36m===== 上下文管理 =====\033[0m")
        print("1. 查看上下文状态")
        print("2. 保存上下文")
        print("3. 清空上下文")
        print("4. 导出上下文")
        print("5. 导入上下文")
        print("0. 返回")
        
        choice = input("请选择操作: ").strip()
        
        if not self.collaboration_mode or not self.collaboration_manager:
            return "协作模式未启用"
        
        if choice == "1":
            context_count = len(self.collaboration_manager.shared_context)
            return f"当前共享上下文: {context_count}条记录"
        
        elif choice == "2":
            if self.collaboration_manager.save_shared_context():
                return "共享上下文已保存"
            else:
                return "保存共享上下文失败"
        
        elif choice == "3":
            if self.collaboration_manager.clear_shared_context():
                return "共享上下文已清空"
            else:
                return "清空共享上下文失败"
        
        elif choice == "4":
            file_name = input("请输入导出文件名 (可选): ").strip()
            if file_name:
                export_path = self.collaboration_manager.context_dir / file_name
            else:
                export_path = None
            return self.collaboration_manager.export_shared_context(export_path)
        
        elif choice == "5":
            print("可用的上下文文件:")
            context_files = list(self.collaboration_manager.context_dir.glob("*.json"))
            for i, file in enumerate(context_files):
                print(f"{i+1}. {file.name}")
            
            try:
                file_choice = int(input("请选择要导入的文件 (编号): "))
                if 1 <= file_choice <= len(context_files):
                    return self.collaboration_manager.import_shared_context(context_files[file_choice-1])
                else:
                    return "无效的选择"
            except ValueError:
                return "输入无效，请输入数字"
        
        elif choice == "0":
            return "已返回"
        
        else:
            return "无效的选择"
    
    def process_requirements(self, requirements):
        """处理用户需求"""
        if requirements.lower() == 'exit':
            return "系统已退出", True
        
        if requirements.lower() == 'help':
            help_text = """
            ### 系统帮助 ###
            1. 输入需求描述，AI将生成操作指令
            2. 支持的操作类型:
               - create_file: 创建文件
               - modify_file: 修改文件
               - delete_file: 删除文件
               - run_command: 执行命令
               - run_code: 运行代码
               - debug_code: 调试代码
               - explain: 解释说明
               - web_server: 启动Web服务器
               - open_browser: 打开浏览器
            3. 系统命令:
               - exit: 退出系统
               - help: 显示帮助
               - config: 配置模型
               - history: 查看历史
               - team_config: 配置团队
               - context_config: 配置上下文
               - context_manage: 管理上下文
            4. 协作命令:
               - team on: 启用协作模式
               - team off: 禁用协作模式
               - team status: 查看团队状态
            """
            return help_text, False
        
        if requirements.lower() == 'config':
            return self.configure_model(), False
        
        if requirements.lower() == 'history':
            return self.show_history(), False
        
        if requirements.lower() == 'team_config':
            return self.configure_team(), False
        
        if requirements.lower() == 'context_config':
            return self.configure_context_settings(), False
        
        if requirements.lower() == 'context_manage':
            return self.manage_context(), False
        
        # 协作模式命令
        if requirements.lower() == 'team on':
            return self.enable_collaboration(), False
            
        if requirements.lower() == 'team off':
            return self.disable_collaboration(), False
            
        if requirements.lower() == 'team status':
            return self.get_team_status(), False
        
        # 如果是协作模式
        if self.collaboration_mode and self.collaboration_manager:
            # 执行协作开发
            result = self.collaboration_manager.orchestrate_development(requirements)
            
            # 记录历史
            self.log_history("协作开发", requirements, result)
            
            # 格式化响应
            response = "\n\033[1;34m=== 多AI协作开发完成 ===\033[0m\n"
            response += result.get("integration", "无整合信息") + "\n"
            
            return response, False
        
        # 单一AI处理模式
        instructions, results = self.generate_instructions(requirements)
        
        # 准备响应
        response = "\n\033[1;34m=== AI推理过程 ===\033[0m\n"
        response += instructions.get("reasoning", "无推理过程") + "\n\n"
        
        response += "\033[1;34m=== 执行结果 ===\033[0m\n"
        for i, result in enumerate(results, 1):
            status = "\033[1;32m✓\033[0m" if result["success"] else "\033[1;31m✗\033[0m"
            response += f"{i}. [{status}] {result['type']}: {result['output']}\n"
        
        # 记录历史
        self.log_history("执行指令", requirements, {
            "instructions": instructions,
            "results": results
        })
        
        return response, False

    
    def show_history(self):
        """显示开发历史"""
        if not self.project_history:
            return "尚无开发历史"
        
        history_str = ""
        for i, entry in enumerate(self.project_history[-5:]):  # 显示最近5条记录
            history_str += f"{i+1}. [{entry['time']}] {entry['action']}: {entry['content'][:50]}"
            if len(entry['content']) > 50:
                history_str += "..."
            history_str += "\n"
        return history_str
    
    def configure_model(self):
        """配置AI模型和API密钥"""
        print("\n\033[1;36m===== 模型配置 =====\033[0m")
        print("支持的AI模型服务:")
        for i, (key, model) in enumerate(self.supported_models.items(), 1):
            print(f"{i}. {model['name']} ({key})")
        print("0. 不使用AI模型 (使用内置逻辑)")
        
        try:
            choice = int(input("\n请选择要使用的模型 (编号): "))
            if choice == 0:
                self.config["selected_model"] = None
                self.save_config()
                return "已设置为使用内置逻辑"
            
            model_keys = list(self.supported_models.keys())
            if 1 <= choice <= len(model_keys):
                selected_key = model_keys[choice-1]
                self.config["selected_model"] = selected_key
                
                # 获取API密钥
                api_key = input(f"请输入{self.supported_models[selected_key]['name']}的API密钥: ").strip()
                if api_key:
                    self.config["api_keys"][selected_key] = api_key
                    self.save_config()
                    return f"{self.supported_models[selected_key]['name']}配置成功!"
                else:
                    return "未提供API密钥，配置未保存"
            else:
                return "无效的选择"
        except ValueError:
            return "输入无效，请输入数字"

def main():
    # 使用当前工作目录创建UserManager
    user_manager = UserManager()
    
    # 用户认证流程
    print("\033[1;34m" + "=" * 70)
    print("        AI 程序员智能开发系统 v7.0 (多AI协作版)")
    print("=" * 70 + "\033[0m")
    
    while not user_manager.current_user:
        print("\n请选择操作:")
        print("1. 登录")
        print("2. 注册")
        print("3. 退出")
        
        choice = input("请输入选项编号: ").strip()
        
        if choice == "1":  # 登录
            username = input("用户名: ").strip()
            password = getpass.getpass("密码: ").strip()
            success, message = user_manager.login(username, password)
            if success:
                print(f"\033[1;32m{message}\033[0m")
            else:
                print(f"\033[1;31m{message}\033[0m")
                
        elif choice == "2":  # 注册
            username = input("用户名: ").strip()
            password = getpass.getpass("密码: ").strip()
            confirm = getpass.getpass("确认密码: ").strip()
            
            if password != confirm:
                print("\033[1;31m两次输入的密码不一致\033[0m")
                continue
                
            success, message = user_manager.register(username, password)
            if success:
                print(f"\033[1;32m{message}\033[0m")
                # 自动登录新用户
                user_manager.login(username, password)
            else:
                print(f"\033[1;31m{message}\033[0m")
                
        elif choice == "3":  # 退出
            print("系统已退出")
            return
            
        else:
            print("\033[1;31m无效选项，请重新输入\033[0m")
    
    # 初始化AI开发者环境
    user_dir = user_manager.get_user_dir()
    if not user_dir:
        print("\033[1;31m无法获取用户目录，请重新登录\033[0m")
        return
        
    ai_dev = AIDeveloper(user_dir)
    ai_dev.display_banner(user_manager.current_user)
    
    while True:
        try:
            requirements = input("\n\033[1;32m请输入需求 (\033[1;33m'help' 显示帮助\033[1;32m): \033[0m")
            
            if requirements.lower() == 'logout':
                result, message = user_manager.logout()
                print(f"\033[1;32m{message}\033[0m")
                # 重新启动主函数以返回登录界面
                main()
                return
                
            response, should_exit = ai_dev.process_requirements(requirements)
            
            print("\033[1;36m" + response + "\033[0m")
            
            if should_exit:
                break
                
        except KeyboardInterrupt:
            print("\n\033[1;33m操作已中断。输入 'exit' 退出系统。\033[0m")
        except Exception as e:
            print(f"\033[1;31m发生错误: {str(e)}\033[0m")
    
    # 退出前停止Web服务器
    if ai_dev.web_process and ai_dev.web_process.poll() is None:
        ai_dev.web_process.terminate()
    print("\033[1;32m系统已退出\033[0m")

if __name__ == "__main__":
    main()